package com.library.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.library.common.base.ApiResult;
import com.library.common.entity.MyPage;
import com.library.common.utils.PageUtil;
import com.library.entity.*;
import com.library.entity.dto.QueryResourceDto;
import com.library.entity.vo.BookResourceVo;
import com.library.service.*;
import io.swagger.annotations.*;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 首页相关接口
 *
 * @author myg
 * @date 2023-07-19  16:06:24
 */
@RestController
@RequestMapping("/homepage")
@Api(tags = "首页相关", value = "首页相关接口")
public class HomePageController {
    @Autowired
    private BannerService bannerService;
    @Autowired
    private BookDataTypeService bookDataTypeService;
    @Autowired
    private BookTypeService bookTypeService;
    @Autowired
    private RecommendManageService recommendManageService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private ResourceHomeService resourceHomeService;
    @Autowired
    private RUserLikeService rUserLikeService;
    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "获取banner列表【banner投放位置，不传默认返回所有】" +
            " 1 首页轮播图 2 产品页轮播图 3 帮助页轮播图", response = BannerInfo.class)
    @GetMapping("/getBanner")
    public ApiResult<List<BannerInfo>> getBanner(
            @RequestParam(value = "position", required = false) Integer position) {
        LambdaQueryWrapper<BannerInfo> query = new LambdaQueryWrapper<>();
        query.eq(BannerInfo::getStatus, 1);
        if (position != null) {
            query.eq(BannerInfo::getPosition, position);
        }
        List<BannerInfo> list = bannerService.list(query);
        return ApiResult.ok(list);
    }

    @ApiOperation(value = "获取推荐位列表")
    @GetMapping("/getRecommend")
    public ApiResult<List<RecommendManageEntity>> getRecommend() {
        LambdaQueryWrapper<RecommendManageEntity> query = new LambdaQueryWrapper<>();
        query.eq(RecommendManageEntity::getState, 0);
        List<RecommendManageEntity> list = recommendManageService.list(query);
        return ApiResult.ok(list);
    }

    @ApiOperation(value = "查询首页tab分类")
    @GetMapping("/getCategorize")
    public ApiResult getCategorize() {
        LambdaQueryWrapper<BookDataTypeEntity> wrapper = Wrappers.lambdaQuery();
        return ApiResult.ok(bookDataTypeService.list());
    }

    @PostMapping("/getBookByType")
    @ApiOperation(value = "根据tab分类查询该类型内容", response = ResourceEntity.class)
    public ApiResult<MyPage<ResourceEntity>> getBookByType(@RequestBody QueryResourceDto dto) {
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ResourceEntity::getSfRecommend, dto.getBookType());
        if (ObjectUtil.isNotEmpty(dto.getSecondType())) {
            wrapper.eq(ResourceEntity::getSecondType, dto.getSecondType());
        }
        wrapper.orderByDesc(ResourceEntity::getPageView);
        wrapper.orderByDesc(ResourceEntity::getLikeCount);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<ResourceEntity> resourceEntities = resourceService.list(wrapper);
        if (ObjectUtil.isNotEmpty(resourceEntities)) {
            if (!TextUtils.isEmpty(dto.getOpenId())) {
                UserInfo userInfo = userInfoService.getUserByOpenId(dto.getOpenId());
                resourceEntities.forEach(resourceEntity -> {
                    if (userInfo != null) {
                        RUserLike rUserLike = rUserLikeService.getOne(new LambdaQueryWrapper<RUserLike>()
                                .eq(RUserLike::getUserId, Long.valueOf(userInfo.getId())).eq(RUserLike::getResourceId, resourceEntity.getResourceId()));
                        if (rUserLike != null) {
                            resourceEntity.setSfLike(1);
                        } else {
                            resourceEntity.setSfLike(0);
                        }
                    }
                });
            }
        }

        PageInfo<ResourceEntity> info = new PageInfo<>(resourceEntities);
        return ApiResult.ok(PageUtil.PageInfo2MyPage(info));
    }

    @PostMapping("/getBookByTypeExt")
    @ApiOperation(value = "根据tab分类查询该类型内容", response = ResourceEntity.class)
    public ApiResult<MyPage<ResourceHome>> getBookByTypeExt(@RequestBody QueryResourceDto dto) {
//        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(ResourceEntity::getSfRecommend, dto.getBookType());
//        if(ObjectUtil.isNotEmpty(dto.getSecondType())){
//            wrapper.eq(ResourceEntity::getSecondType, dto.getSecondType());
//        }
//        wrapper.orderByDesc(ResourceEntity::getPageView);
//        wrapper.orderByDesc(ResourceEntity::getLikeCount);
//        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
//        List<ResourceEntity> resourceEntities = resourceService.list(wrapper);
//
//        if (ObjectUtil.isNotEmpty(resourceEntities)) {
//            resourceEntities.forEach(resourceEntity -> {
//                UserInfo userInfo = userInfoService.getUserByOpenId(dto.getOpenId());
//                if (userInfo != null) {
//                    RUserLike rUserLike = rUserLikeService.getOne(new LambdaQueryWrapper<RUserLike>()
//                            .eq(RUserLike::getUserId, Long.valueOf(userInfo.getId())).eq(RUserLike::getResourceId, resourceEntity.getResourceId()));
//                    if (rUserLike != null) {
//                        resourceEntity.setSfLike(1);
//                    } else {
//                        resourceEntity.setSfLike(0);
//                    }
//                }
//            });
//        }
//
//        PageInfo<ResourceEntity> info = new PageInfo<>(resourceEntities);
//        return ApiResult.ok(PageUtil.PageInfo2MyPage(info));

        LambdaQueryWrapper<ResourceHome> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ResourceHome::getSfRecommend, dto.getBookType());
        if (ObjectUtil.isNotEmpty(dto.getSecondType())) {
            wrapper.eq(ResourceHome::getSecondType, dto.getSecondType());
        }
        wrapper.orderByDesc(ResourceHome::getPageView);
        wrapper.orderByDesc(ResourceHome::getLikeCount);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<ResourceHome> resourceEntities = resourceHomeService.list(wrapper);

        if (ObjectUtil.isNotEmpty(resourceEntities)) {
            if (!TextUtils.isEmpty(dto.getOpenId())) {
                UserInfo userInfo = userInfoService.getUserByOpenId(dto.getOpenId());
                resourceEntities.forEach(resourceEntity -> {
                    if (userInfo != null) {
                        RUserLike rUserLike = rUserLikeService.getOne(new LambdaQueryWrapper<RUserLike>()
                                .eq(RUserLike::getUserId, Long.valueOf(userInfo.getId())).eq(RUserLike::getResourceId, resourceEntity.getResourceId()));
                        if (rUserLike != null) {
                            resourceEntity.setSfLike(1);
                        } else {
                            resourceEntity.setSfLike(0);
                        }
                    }
                });
            }
        }

        PageInfo<ResourceHome> info = new PageInfo<>(resourceEntities);
        return ApiResult.ok(PageUtil.PageInfo2MyPage(info));
    }

    @ApiOperation(value = "通过id查询具体详情（包含评论、推荐）", response = BookResourceVo.class)
    @PostMapping("/detail")
    public ApiResult getById(@RequestBody QueryResourceDto dto, HttpServletResponse response) {
        response.setHeader("Accept-Ranges", "bytes");
        return ApiResult.ok(resourceService.detail(dto));
    }
}
